import React, { FC, useEffect, useState, useRef } from 'react'
import { Form, message, Radio, Select } from 'antd'
import { EditableProTable, ProColumns } from '@ant-design/pro-table'
import { addProField, deleteProField, getProFieldList, updateProField } from '@/services/proField'
import { Config } from '@utils/Constants'
import { getFileList } from '@/services/proFile'

interface FieldFormProps {
  fileId:string,
  projectId:string,
}

const base = Config.DATA_TYPE_LIST
const FieldForm: FC<FieldFormProps> = (props) => {

  const ref = useRef<any>()
  const { fileId,projectId } = props
  const [editableKeys, setEditableRowKeys] = useState<any>([])
  const [fieldList, setFieldList] = useState<any>([])
  const [typePathList,setTypePathList] = useState<any>(base);
  const [voList,setVoList] = useState<any>()

  useEffect(() => {
      // 获取Vo字段列表
    getFileList({project_id:projectId,file_type:'vo'}).then(res=>{
      if (res.code === 10000) {
        const data = res.data;
        const nameList = [];
        for (const item of data) {
          nameList.push(item.name);
        }
        setVoList(nameList);
      }
    })
  }, [fileId])

  const columns: ProColumns<any>[] = [
    {
      title: '名称',
      dataIndex: 'name',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项'
          }
        ]
      }
    },
    {
      title: '简介',
      dataIndex: 'comment',
      hideInSearch: true,
    },
    {
      title: '字段类型',
      dataIndex: 'data_type',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必选项'
          }
        ]
      },
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        return <Radio.Group onChange={(v) => setTypePath(v.target.value,form)}>
          <Radio.Button value="base">base</Radio.Button>
          <Radio.Button value="vo">vo</Radio.Button>
          <Radio.Button value="T">T</Radio.Button>
        </Radio.Group>
      }
    },
    {
      title: '数据类型',
      dataIndex: 'type_path',
      hideInSearch: true,
      valueType: 'select',
      // initialValue:null,
      // valueEnum:typePathList,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必选项'
          }
        ]
      },
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        return <Select placeholder="请选择" style={{width:100}} >
          {typePathList.map((item:any) =>(
          <Select.Option value={item}>{item}</Select.Option>
          ))}
        </Select>
      },
      render:(_,record:any) => <span>{record.type_path}</span>,
    },
    {
      title: '集合类型',
      dataIndex: 'collection_type',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必选项'
          }
        ]
      },
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        return <Radio.Group>
          <Radio.Button value="single">single</Radio.Button>
          <Radio.Button value="list">list</Radio.Button>
          <Radio.Button value="set">set</Radio.Button>
          <Radio.Button value="map">map</Radio.Button>
        </Radio.Group>
      }
    },
    {
      title: '操作',
      valueType: 'option',
      width: 150,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action.startEditable?.(record.id)
          }}
        >
          编辑
        </a>
      ]
    }
  ]

  const setTypePath = (val:any,form:any) => {
    if ('base' === val) {
      setTypePathList(base);
    }else if ('vo' === val) {
      setTypePathList(voList);

    }else if ('T' === val) {
      setTypePathList(['T']);
    }
  }


  return (
    <>
        <EditableProTable
          size='small'
          actionRef={ref}
          rowKey="id"
          columns={columns}
          request={async () => getProFieldList({ file_id: fileId }).then((res) => {
            setFieldList(res.data)
            return res
          })}
          value={fieldList}
          headerTitle="Vo字段"
          search={false}
          options={{ search: false }}
          editable={{
            editableKeys,
            onSave: async (key: any, val: any) => {
              delete val.index
              if (val.id) {
                delete val.create_time
                await updateProField(val).then((res) => {
                  if (res.code === 10000) {
                    ref.current.reload()
                    message.success('修改成功！')
                  }
                })
              } else {
                val.file_id = fileId;
                await addProField(val).then((res) => {
                  if (res.code === 10000) {
                    ref.current.reload()
                    message.success('添加成功！')
                  }
                })
              }
            },
            onDelete: async (value: any) => deleteProField({ id: value }).then((res) => {
              if (res.code === 10000) {
                message.success('删除成功！')
                ref.current.reload()
              }
            }),
            onChange: setEditableRowKeys
          }}
        />
    </>
  )
}

export default FieldForm
